package util;

import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import utils.DateUtil;
import utils.FileUtil;

public class LogUtil {

	private static boolean FLAG = false;
	private static String PATH = null;
	private static String LINE = null;
	private static String SIGN = "www";

	static {
		if ("linux".equalsIgnoreCase(System.getProperty("os.name"))) {
			PATH = "/usr/logs/" + SIGN;
			LINE = "\n";
			FLAG = false;
		} else {
			PATH = "c:/logs/" + SIGN;
			LINE = "\r\n";
			FLAG = true;
		}
	}

	public static List<File> list(String type) {
		try {
			List<File> list = Arrays.asList(new File(PATH + "/" + type + "/").listFiles());
			Collections.sort(list, new Comparator<File>() {
				public int compare(File f1, File f2) {
					return f2.getName().compareTo(f1.getName());
				}
			});
			return list;
		} catch (Exception e) {
			return null;
		}
	}

	public static String get(String type, String name) {

		String filePath = PATH + "/" + type + "/";
		String fileName = name;
		String fileInfo = "";
		try {
			fileInfo = FileUtil.read(filePath, fileName);
		} catch (Exception e) {
			System.out.println("logging failure");
		}
		if (FLAG) {
			System.out.println(fileInfo);
		}
		return fileInfo;
	}

	public static void log(String type, String name, String info) {
		if (FLAG) {
			System.out.println(info);
		}
		String filePath = PATH + "/" + type + "/";
		String fileName = name;
		String fileInfo = DateUtil.format(new Date(), "HHmmss") + " " + info + LINE;
		try {
			FileUtil.append(filePath, fileName, fileInfo);
		} catch (Exception e) {
			System.out.println("logging failure");
		}
	}

	public static void login(String info) {
		log("login", DateUtil.format(new Date(), "yyyy_MM_dd"), info);
	}

	public static void operate(String info) {
		log("operate", DateUtil.format(new Date(), "yyyy_MM_dd"), info);
	}
	
	public static void exception(String info) {
		log("exception", DateUtil.format(new Date(), "yyyy_MM_dd"), info);
	}

}
